using Glpt.Common;
using Glpt.Data;
using System;
using System.Data;
using System.IO;

namespace Glpt.Task
{
    /// <summary>
    /// 检测BCP文件任务
    /// </summary>
    public class BCPFileTask
    {
        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public BCPFileTask()
        {
        }
        /// <summary>
        /// 测试接口
        /// </summary>
        /// <param name="function_id">功能号</param>
        /// <param name="tradedate">业务日期</param>
        public void SetParams(string function_id, string tradedate)
        {
            SetParams(0, function_id, "", tradedate);
        }
        /// <summary>
        /// 参数设置
        /// </summary>
        /// <param name="db_no">数据库编号</param>
        /// <param name="function_id">功能编号</param>
        /// <param name="task_id">任务编号</param>
        /// <param name="tradedate">业务日期</param>
        public void SetParams(int db_no, string function_id, string task_id, string tradedate)
        {
            string dirSep = DataFuns.DirSeparator;
            BaseInterFace gji = new BaseInterFace(db_no);
            DataTable dtp = gji.ExecSelect("SELECT * FROM TB_CHECK_LIST WHERE TASK_FUNCTION_ID=" + function_id + " AND ENABLE_FLAG='1'");
            foreach (DataRow dr in dtp.Rows)
            {
                string CHECK_CONTENT = dr["CHECK_CONTENT"].ToString();
                int idx = CHECK_CONTENT.LastIndexOf(dirSep);
                if (idx < 0) throw new Exception("路径错误：" + CHECK_CONTENT);
                string PATH_NAME = Funcs.ReplaceWord(CHECK_CONTENT.Substring(0, idx), tradedate);
                string FLAG_NAME = Funcs.ReplaceWord(CHECK_CONTENT.Substring(idx + 1), tradedate);
                string FILE_PATH = Funcs.ReplaceWord(dr["NOTICE_TITLE"].ToString(), tradedate);
                string CHECK_ID = dr["CHECK_ID"].ToString();
                string[] ex_serverid = dr["NOTICE_CONTENT"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string filename = "";
                string[] files = Directory.GetFiles(PATH_NAME, FLAG_NAME, SearchOption.TopDirectoryOnly);
                foreach (string file in files)//找最后一次导出的文件
                {
                    if (file.CompareTo(filename) > 0)
                    {
                        filename = file;
                    }
                }
                if (filename.Length > 0)
                {
                    FileInfo fi = new FileInfo(filename);
                    string filepath = FILE_PATH.Replace("@SOURCE_NO", fi.Name.Substring(8, 4)).Replace("@BATCH_NO", fi.Name.Substring(12, 2));
                    if (!Directory.Exists(filepath)) throw new Exception("目录没有找到：" + filepath);
                    files = Directory.GetDirectories(filepath, "*", SearchOption.TopDirectoryOnly);
                    string sql = "DELETE FROM TB_BCP_FILE WHERE TRADEDATE=" + gji.ParamChar + "tradedate AND PATH_ID=" + gji.ParamChar + "PATH_ID";
                    DbParamCollection sql_params = new DbParamCollection();
                    sql_params.Add(new DbParam("TRADEDATE", tradedate, DbParamType.VarChar, false));
                    sql_params.Add(new DbParam("PATH_ID", CHECK_ID, DbParamType.VarChar, false));
                    gji.ExecUpdate(sql, sql_params);
                    sql_params.Add(new DbParam("PATH_NAME", DBNull.Value, DbParamType.VarChar, false));
                    sql_params.Add(new DbParam("FILE_TIME", fi.CreationTime, DbParamType.DateTime, false));
                    sql_params.Add(new DbParam("CHECK_TIME", DateTime.Now, DbParamType.DateTime, false));
                    sql_params.Add(new DbParam("FILE_FLAG", DBNull.Value, DbParamType.VarChar, false));
                    foreach (string file in files)
                    {
                        DirectoryInfo dir = new DirectoryInfo(file);
                        sql = "INSERT INTO TB_BCP_FILE(TRADEDATE,PATH_ID,PATH_NAME,FILE_TIME,CHECK_TIME,FILE_FLAG) VALUES(" + gji.ParamChar + "TRADEDATE," + gji.ParamChar + "PATH_ID," + gji.ParamChar + "PATH_NAME," + gji.ParamChar + "FILE_TIME," + gji.ParamChar + "CHECK_TIME," + gji.ParamChar + "FILE_FLAG)";
                        sql_params[2].Value = dir.FullName + dirSep;
                        sql_params[5].Value = IsContain(ex_serverid, dir.Name) ? "0" : "1";
                        gji.ExecUpdate(sql, sql_params);
                    }
                }
            }
        }

        private bool IsContain(string[] list, string val)
        {
            bool is_con = false;
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Equals(val))
                {
                    is_con = true;
                    break;
                }
            }
            return is_con;
        }

        /// <summary>
        /// 释放内存
        /// </summary>
        public void Dispose()
        {
            try
            {
                GC.Collect();
            }
            catch { }
        }

        /// <summary>
        /// 析构函数
        /// </summary>
        ~BCPFileTask()
        {
            Dispose();
        }
    }
}
